<template>
  <div class="page product-details">
    <div class="scroll-view">
      <customHeader class="_header" @leftCallBack="handleBack" v-if="returnBtnBag"></customHeader>
      <customHeader @leftCallBack="handleBack" v-if="!returnBtnBag"></customHeader>
      <div class="page-body" ref="pageBody"  :style="{marginTop:headerheight+'px'}">
        <div class="ct-body" ref="ctBody">
          <div class="img-swipe-box">
            <mt-swipe :auto="0" :show-indicators="detailInfo.linkImages.length>1?true:false" class="img-swipe">
              <mt-swipe-item v-for="(item,index) in detailInfo.linkImages" :key="index">
                <img class="mainImg" :src="imgFormate(item)" alt>
              </mt-swipe-item>
            </mt-swipe>
            <div class="img-info">
              <p>{{detailInfo.machineToolName}}</p>
              <p>{{detailInfo.machineToolDescription}}</p>
              <p>
                <span>¥ {{detailInfo.currentPrice}}</span>
                <span>¥ {{detailInfo.originalPrice}}</span>
              </p>
            </div>
          </div>
          <ul class="linebar-list-num">
            <li>
              <div class="context-left">
                <span class="main-text text-left">购买数量</span>
              </div>
              <div class="context-right">
                <div class="num-box">
                  <i
                    class="zhk-js"
                    :class="minClass ? 'activeClass' : 'disabledClass' "
                    @click="min"
                  ></i>
                  <input class="buy-num" name type="number" v-model="counter">
                  <i
                    class="zhk-zj"
                    :class="addClass ? 'activeClass' : 'disabledClass' "
                    @click="add"
                  ></i>
                </div>
              </div>
            </li>
          </ul>
          <div class="form-title">邮寄到</div>
          <ul class="linebar-list" v-show="!receiverInfo.linkman">
            <li @click="fillAddress">
              <div class="context-left">
                <span>收货人信息</span>
              </div>
              <div class="context-right">
                <i class="zhk-list_rarrow"></i>
              </div>
            </li>
          </ul>
          <ul class="recive-info" v-show="receiverInfo.linkman">
            <li @click="fillAddress">
              <div>
                <span class="text-left">{{receiverInfo.linkman}}</span>
                <span class="text-right">{{receiverInfo.mobile}}</span>
              </div>
              <div>
                <p class="text-left">{{joinDetailArea}}{{receiverInfo.address}}</p>
                <i class="zhk-list_rarrow text-right"></i>
              </div>
            </li>
          </ul>
          <div class="form-title">附加信息</div>
          <ul class="form-style">
            <li>
              <span class="required">备注</span>
              <div>
                <inputClear
                  @blur="fieldValidate('remarksValue')"
                  v-model="remarksValue"
                  placeholder="选填"
                  :max="200"
                  :maxlength="200"
                ></inputClear>
              </div>
            </li>
            <li>
              <span class="required">邀请码</span>
              <div>
                <inputClear
                  @blur="fieldValidate('invitationCode')"
                  v-model="invitationCode"
                  placeholder="选填"
                  :max="15"
                  :maxlength="15"
                ></inputClear>
              </div>
            </li>
          </ul>
          <div class="form-title-center">
            <i :class="isChecked?'zhk-ty':'zhk-wxz'" @click="toggleCheckbox"/>
            <label>
              我已阅读并同意
              <span @click="jumpToserviceContract">《同福商家产品服务协议》</span>
            </label>
          </div>
        </div>
      </div>
      <ul class="total-buy">
        <li class>
          <p>
            合计金额：
            <span>¥ {{totalMoney}}</span>
          </p>
          <p @click="createOrder">立即购买</p>
        </li>
      </ul>
    </div>
    <receiverInfo ref="recInfo" @getReceiveInfo="updateReceiveInfo"></receiverInfo>
    <serviceContract ref="servContract"></serviceContract>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import config from "../../base/profile/config.json";
import jsBridge from "../../tools/jsBridge.js";
import { Swipe, SwipeItem, Toast, MessageBox } from "mint-ui";
import inputClear from "../../components/inputClear/inputClear";
import receiverInfo from "./receiverInfo";
import serviceContract from "./serviceContract";

Vue.component(Swipe.name, Swipe);
Vue.component(SwipeItem.name, SwipeItem);

export default {
  name: "productDetails",
  data() {
    return {
      headerheight:0,
      remarksValue: "", //备注
      invitationCode: "", //邀请码
      remarkValue: "",
      inviteCodeValue: "",
      counter: 1, //购买数量
      minClass: false,
      addClass: true,
      isChecked: true,

      receiverInfo: {
        //获取组件得到的信息
        linkman: "",
        mobile: "",
        defaultVal: "",
        address: ""
      },
      totalMoney: "", //合计金额
      orderId: "",
      param: {},
      joinDetailArea: "",
      refuseClick: false,
      returnBtnBag: true,
      detailInfo: {
        commidyType: null,
        currentPrice: 0,
        id: null,
        linkImages: [],
        machineToolDescription: "",
        machineToolName: "",
        machineType: null,
        mainImage: "",
        originalPrice: null,
      },
    };
  },
  watch: {
    counter(newValue, oldValue) {
      if (newValue <= 1) {
        if (newValue < 1) {
          this.counter = 1;
          Toast("数量超过限制范围");
        }
        this.minClass = false;
        this.addClass = true;
      } else if (newValue > 1 && newValue < 999) {
        this.minClass = true;
        this.addClass = true;
      } else {
        if (newValue > 999) {
          this.counter = 999;
          Toast("数量超过限制范围");
        }
        this.minClass = true;
        this.addClass = false;
      }
      this.totalMoney = newValue *10000* this.detailInfo.currentPrice/10000;
    }
  },
  methods: {
    handleBack() {
      if (this.$refs.recInfo.popupReciverVisible) {
        this.$refs.recInfo.popupHide();
      } else if (this.$refs.servContract.popupServiceVisible) {
        this.$refs.servContract.popupHide();
      } else {
        if (String(this.$route.query.close) == 'true') {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    imgFormate(v) {
      return config.shopImgUrlPrefix + v;
    },
    // 跳转到填写收货人信息页
    fillAddress() {
      this.$refs.recInfo.popupShow();
    },
    // 购买数量计数
    min() {
      if (this.counter > 1) {
        this.counter = parseInt(this.counter) - 1;
      }
    },
    add() {
      if (this.counter < 999) {
        this.counter = parseInt(this.counter) + 1;
      }
    },

    // 切换勾选协议
    toggleCheckbox() {
      this.isChecked = !this.isChecked;
    },
    updateReceiveInfo(data) {
      if (data) {
        this.receiverInfo.linkman = data.linkman;
        this.receiverInfo.mobile = data.mobile;
        this.receiverInfo.defaultVal = data.defaultVal;
        this.joinDetailArea = data.defaultVal[0].name + data.defaultVal[1].name + data.defaultVal[2].name;
        this.receiverInfo.address = data.address;
      }
    },
    encodePayInfo(string) {
      let str = string;
      let temp = str.split("&");
      let resultArray = [];
      for (let index = 0; index < temp.length; index++) {
        let item;
        if (temp[index].startsWith("sign=")) {
          item = [];
          item.push("sign");
          item.push(encodeURIComponent(temp[index].slice(5)));
        } else {
          item = temp[index].split("=");
          item[1] = encodeURIComponent(item[1]);
        }
        resultArray.push(item.join("="));
      }
      return resultArray.join("&");
    },
    // 下单
    createOrder(extParams) {
      if (String(this.counter).indexOf(".")!=-1) {
          Toast("请输入正确的购买数量");
          return;
      }
      if (!this.receiverInfo.linkman) {
        Toast("请填写收货人信息");
        return;
      }
      if (!this.isChecked) {
        Toast("请阅读并同意《同福商家产品服务协议》");
        return;
      }
      if (!this.isNomalLetter(this.invitationCode)) {
        Toast("请输入6～15位字符，数字+字母");
        return;
      }
      if (this.refuseClick) {
        return;
      } else {
        this.refuseClick = true;
        const param = {
          name: this.receiverInfo.linkman,
          phoneNum: this.receiverInfo.mobile,
          areaList: this.receiverInfo.defaultVal,
          address: this.receiverInfo.address, //详细地址
          // totalMoney: this.totalMoney,
          // realTotalMoney: this.totalMoney,
          // maXianShengDeviceNum: this.machineToolId == 17 ? this.counter : "",
          // maKaLongDeviceNum: this.machineToolId == 18 ? this.counter : "",
          descMsg: this.remarksValue, //订单备注
          inviteCode: this.invitationCode, //-邀请码
          deviceModelList: [{ machineToolId: this.detailInfo.machineType, deviceNum: this.counter }],
          commidyType: this.detailInfo.commidyType
        };
        if(extParams&&extParams.warningAgree==1) {
          param.warningAgree = 1;
        }
        this.ajax({
          url: "newapp/orderService/createOrder.do",
          type: "post",
          data: param,
          controlLoading: true
        }).then(res => {
          this.refuseClick = false;
          if(res.success && res.resultObject) {
            this.orderId = res.resultObject.orderId;
            //调起支付接口
            jsBridge.tradePay(
              {
                payType: "alipay",
                orderInfo: this.encodePayInfo(res.resultObject.orderInfo)
              },
              result => {
                if (result.resultObject.resultStatus == "9000") {//支付成功
                  // this.forPayment();
                  this.$router.push({ path: "/mallList/productDetails/payResult", query: { type: "true", toRouterNum: 1, toRouterRecordNum: 1 } });
                } else if (result.resultObject.resultStatus == "4000") {//支付失败
                  // Toast(result.msg);
                  this.$router.push({ path: "/mallList/productDetails/payResult", query: { type: "false", toRouterNum: 1, toRouterRecordNum: 1 } });
                } else {
                  this.$router.push({ path: "/mallList/orderRecord/orderDetails", query: { orderId: this.orderId } });
                }
              }
            );
          }else {
            if(res.code==5005) {
              this.handleConfirmOrder(res.msg);
              return;
            }
            Toast(res.msg);
          }
        }).catch(err => {
          this.refuseClick = false;
        });
      }
    },
    handleConfirmOrder(msg) {
      MessageBox({
        title: "温馨提示",
        confirmButtonText: "仍然订购",
        message: msg,
        showCancelButton: true,
        closeOnClickModal: false
      }).then(action => {
        if(action=="confirm") {
          this.createOrder({warningAgree:1})
        }
      });
    },
    // 邀请码验证特殊字符
    isNomalLetter(value) {
      let result = false;
      const test = /^[a-zA-Z0-9]+$/;
      if (value && (value.length < 6 || value.length > 15 || !test.test(value))) {
        result = false;
      } else {
        result = true;
      }
      return result;
    },
    //字段校验
    fieldValidate(fieldName) {
      let isValidate = true;
      //邀请码
      if (fieldName === "invitationCode") {
        const fieldValue = this.invitationCode;
        // this.invitationCode = this.invitationCode.substr(0, 15);
        if (fieldValue) {
          if (!this.isNomalLetter(fieldValue)) {
            isValidate = false;
            Toast("请输入6～15位字符，数字+字母");
            return isValidate;
          }
        }
      }
    },
    // 跳转到服务协议
    jumpToserviceContract() {
      this.$refs.servContract.popupShow();
    },
    eventListener() {
      document.getElementsByTagName("body")[0].className = "activeBody";
      if (this && this.$refs && this.$refs.ctBody && this.$refs.ctBody.clientHeight) {
        this.$refs.pageBody.scrollTop = this.$refs.ctBody.clientHeight;
      }
      setTimeout(() => {
        document.getElementsByTagName("body")[0].className = "";
      }, 100);
    },
    // 获取商品详情信息
    loadData() {
      this.ajax({
        url: `newapp/orderService/deviceDetail.do?machineToolType=` + this.$route.query.machineType,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.success && res.resultObject) {
            this.detailInfo = res.resultObject;
            this.totalMoney = res.resultObject.currentPrice;
          } else {
            Toast(res.msg);
          }
        })
        .catch(err => {

        });
    }
  },
  created() {
    // 获取商品详情
    this.loadData();
  },
  mounted() {

    // const getDetailObj = JSON.parse(sessionStorage.detailObj);
    // this.packageName = getDetailObj.packageName;
    // this.packageDescription = getDetailObj.packageDescription;
    // this.currentPrice = getDetailObj.currentPrice;
    // this.originalPrice = getDetailObj.originalPrice;
    // this.totalMoney = getDetailObj.currentPrice;
    // this.machineToolId = getDetailObj.machineToolId;

    // this.getReceiverInfo();

    let imgSwipeheight = document.querySelector(".img-swipe").clientHeight;
    const headerheight = document.querySelector(".header").clientHeight;
    this.headerheight=0-headerheight;
    imgSwipeheight = imgSwipeheight - headerheight;
    let returnBtn = this.$refs.pageBody;
    // 屏幕上下滑动切换返回按钮样式
    returnBtn.addEventListener(
      "scroll",
      () => {
        this.returnBtnBag = returnBtn.scrollTop > imgSwipeheight ? false : true;
      },
      false
    );

    // 手机端点击输入框页面整体上滑
    // window.onresize = () => {
    //   returnBtn.addEventListener(
    //   // return (() => {

    //     document.getElementsByTagName("body")[0].className = "activeBody";
    //     // let returnBtn = this.$refs.pageBody;
    //        debugger
    //     this.$refs.pageBody.scrollTop(this.$refs.ctBody.clientHeight);
    //     setTimeout(() => {

    //       document.getElementsByTagName("body")[0].className = "";
    //     }, 100);
    //   // })(this);
    // // };
    //   )
    // let self = this;
    window.addEventListener("resize", this.eventListener, false);
  },
  destroyed() {
    window.removeEventListener("resize", this.eventListener, false);
  },
  components: {
    customHeader,
    inputClear,
    receiverInfo,
    serviceContract
  }
};
</script>
<style lang='scss' scoped>
@import "mall";
</style>
<style lang='scss'>
.mint-swipe-indicator {
  background: #fff;
  opacity: 0.7;
}
.mint-swipe-indicators {
  .mint-swipe-indicator.is-active {
    background: #e02424 !important;
  }
}
</style>
